package com.tsdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsdp.dto.Result;
import com.tsdp.dto.UserDTO;
import com.tsdp.entity.Blog;
import com.tsdp.entity.User;
import com.tsdp.interceptor.RefreshInterceptor;
import com.tsdp.mapper.BlogMapper;
import com.tsdp.mapper.UserMapper;
import com.tsdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsdp.service.IUserService;
import com.tsdp.utils.SystemConstants;
import com.tsdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tsdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 范大晨
 * @since 2022-11-9
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        records.forEach(blog -> {
            queryAddUser2Blog(blog);
            isLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        Set<String> userIds = redisTemplate.opsForZSet().range(key, 0, 4);
        //判空
        if (userIds == null || userIds.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        String strIds = StrUtil.join(",", userIds);
        log.info("strIds==>{}", strIds);
        List<Long> ids = userIds.stream().map(Long::valueOf).collect(Collectors.toList());
        //List<User> users = userService.listByIds(ids);
        List<User> users = userMapper.selectListByIds(ids, strIds);
        log.info("users==>{}", users);
        List<UserDTO> userDTOS = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    private void isLiked(Blog blog) {
        String key = BLOG_LIKED_KEY + blog.getId();
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return;
        }
        Long userId = user.getId();
        if (userId != null) {
            Double score = redisTemplate.opsForZSet().score(key, userId.toString());
            if (score != null) {
                blog.setIsLike(Boolean.TRUE);
            }
        }
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        queryAddUser2Blog(blog);
        return Result.ok(blog);
    }

    @Override
    public Result likeBlog(Long id) {
        // 修改点赞数量
//        update().setSql("liked = liked + 1").eq("id", id).update();
        String key = BLOG_LIKED_KEY + id;
        Long userId = UserHolder.getUser().getId();
        // 判断当前用户是否已点赞
        Double score = redisTemplate.opsForZSet().score(key, userId.toString());

        if (score == null) {
            //未点赞 存入redis
            redisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            //写入数据库
            update().setSql("liked=liked+1").eq("id", id).update();
        } else {
            //已点赞
            //修改数据库
            boolean isUpdate = update().setSql("liked=liked-1").eq("id", id).update();
            //从redis删除
            if (isUpdate) {
                redisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    private void queryAddUser2Blog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
